package servise

import (
	"fmt"
	"hxy/repo/config"
	"hxy/repo/database"
	errors "hxy/repo/error"
	. "hxy/repo/model"
	"hxy/repo/monitor"
	"os"
	"strconv"

	"github.com/emicklei/go-restful/v3"
)

func HandleCreateGitModel(request *restful.Request, response *restful.Response) {
	// Retrieve you data in one line of code!
	var gitmodel = new(GitModel)
	if err := request.ReadEntity(gitmodel); err != nil {
		errors.HandleInternalError(response, err)
		return
	}
	git_model := GitModel{
		Name:   gitmodel.Name,
		Url:    gitmodel.Url,
		Path:   gitmodel.Path,
		AuthID: gitmodel.AuthID,
	}
	//TODO 判定是否有效
	//使用默认路径

	if len(git_model.Path) < 2 {
		git_model.Path = config.GitReposDir + "/" + git_model.Name + fmt.Sprint(git_model.ID)
		//log.Println(_repo.Path)
	}
	err := os.MkdirAll(git_model.Path, 0750)

	if err != nil {
		//err : can't mkdir the giben path
		errors.HandleInternalError(response, err)
		return
	}
	err = database.CreateGitRepo(&git_model)
	if err != nil {
		errors.HandleInternalError(response, err)
		return
	}
	//gitmanager : monitor.Gitmanager
	gitmanager := monitor.GitManager{
		Repo: git_model,
	}
	if gitmodel.AuthID != 0 {
		git_auth, re := database.AntuById(gitmodel.AuthID)
		if re.Error != nil {
			errors.HandleInternalError(response, re.Error)
			return
		}
		gitmanager.Auth = git_auth
	}

	go gitmanager.CloneRepos()
	response.WriteAsJson(gitmodel)

}
func HandlerGetAllGitModel(request *restful.Request, response *restful.Response) {
	// Retrieve you data in one line of code!
	all, dbresult := database.GetAllGitRepo()
	if dbresult.Error != nil {
		errors.HandleInternalError(response, dbresult.Error)
		return
	}
	response.WriteAsJson(all)

}
func HandlerDeleteGitModel(request *restful.Request, response *restful.Response) {
	var id = request.PathParameter("id")
	aid, err := strconv.Atoi(id)
	if err != nil {
		errors.HandleInternalError(response, err)
	}
	re := database.GitDeleteId(aid)
	if re.Error != nil {
		errors.HandleInternalError(response, re.Error)
	}
	if re.RowsAffected == 0 {
		response.WriteAsJson(false)
	} else {
		response.WriteAsJson(true)
	}

}
func HandleMapManager(request *restful.Request, response *restful.Response) {
	// Retrieve you data in one line of code!
	all, dbresult := monitor.GetAllGitMonitor()
	if dbresult.Error != nil {
		errors.HandleInternalError(response, dbresult.Error)
	} else {
		response.WriteAsJson(all)
	}
}

func HandlerGetGitModelByid(request *restful.Request, response *restful.Response) {
	var id = request.PathParameter("gitid")
	aid, err := strconv.Atoi(id)
	if err != nil {
		errors.HandleInternalError(response, err)
	}
	git_model, dbre := database.GitById(aid)
	if dbre.Error != nil {
		errors.HandleInternalError(response, dbre.Error)
	}
	response.WriteAsJson(git_model)

}

// func HandleFileWebsocket(request *restful.Request, response *restful.Response) {
// 	ww := response.ResponseWriter
// 	r := request.Request
// }
